package org.example.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.example.pojo.RpcRequest;
import org.example.pojo.RpcResponse;
import org.example.serializer.JdkSerializer;
import org.example.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class ServiceProxy implements InvocationHandler {
    /**
     * 代理方法
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Serializer jdkSerializer = new JdkSerializer();
        //封装请求对象
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setServiceName(method.getDeclaringClass().getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameters(args);
        rpcRequest.setParameterTypes(method.getParameterTypes());
        //序列化
        byte[] serialize = jdkSerializer.serialize(rpcRequest);
        //发送请求
        HttpResponse execute = HttpRequest.post("http://localhost:8080").body(serialize).execute();
        byte[] bytes = execute.bodyBytes();
        RpcResponse rpcResponse = jdkSerializer.deserialize(bytes, RpcResponse.class);
        return rpcResponse.getData();
    }
}
